#!/bin/sh

# install-deb.sh
#
# Script for installing deb files on any operating system.
# WARNING: Read the warning below before installing.
# Usage: ./install-deb.sh /path/to/example.deb
# License: CC0

# Show warning
echo ''
echo ' ┌─────────────────────────────── WARNING! ───────────────────────────────┐'
echo " │ This script just extracts the package files to your system's /         │"
echo ' │ directory. It does not install dependencies or adopt package to your   │'
echo ' │ init system. It will not update by itself with the system, so you have │'
echo ' │ to update it manually when a new version comes along.                  │'
echo ' │ Depending on what distro you are on, it may fail or break your system. │'
echo ' │ Please consider backing up your system. You have been warned.          │'
echo ' └────────────────────────────────────────────────────────────────────────┘'
echo ''

# Variables
TMPPATH='/tmp/debextract'
DEBFILEPATH=$(realpath $1)
FAIL=0

# Check requirements and input file
if [ -z "$(command -v ar)" ]; then
	echo '== This script uses ar command from binutils. Please install binutils package and continue.'
	FAIL=51
fi
if [ -z "$(command -v tar)" ]; then
	echo '== This script uses tar command. Please install tar package and continue.'
	FAIL=52
fi
if [ -z "$1" ]; then
	echo '== No deb file has been passed. Please run this script with a deb filename. e.g.'
	echo "  $0 example-1.2.3.deb"
	FAIL=53
fi
if [ ! -f "$1" ]; then
	echo '== The deb file '"$1"' does not exist.'
	FAIL=54
fi
if [ "$FAIL" -gt 0 ]; then
	exit "$FAIL"
fi

# Make temporary directory
mkdir -p "$TMPPATH"
# If it had files from previous attempt, delete them
rm -rf "$TMPPATH/*"
# cd into temporary path
cd "$TMPPATH"

# Extract data from deb
echo '== Extracting data.tar.xz from deb...'
echo '== This is just extracting, you will be asked to install later...'
ar -x "$DEBFILEPATH" data.tar.xz

# Prompt to install
echo -n '== Data inside deb has been extracted and is ready to be installed. Are you sure you want to install it on this system? [y/N] '
read answer

# Install (or not) based on answer
if [ "$answer" != "${answer#[Yy]}" ] ;then
	if [[ $(id -u) -ne 0 ]] ; then
		echo '== Installing...'
		tar xvf data.tar.xz -C /
	else
		echo '== The script was not run as root user or using sudo. Trying to run with sudo...'
		sudo tar xvf data.tar.xz -C /
	fi
	echo '== Deleting temporary files...'
	rm -rf "$TMPPATH/*"
	echo '== Installation finished. Please make sure you install all the dependencies manually before running the program.'
else
	echo '== Skipping installation. Exiting...'
	exit 45
fi
